<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Email_sender extends MY_Email {
	var $CI;
	var $fromEmail = "";
	var $toEmail = "";
	var $subject = "";
	var $body = "";
	var $emailTitle = "";
	var $attachment = "";
	
	function __construct( $config = array() ){
		parent::__construct($config);
		$this->CI = & get_instance();
		$this->setFromEmail(Settings_class::get('server_email'));
		$this->setEmailTitle("HighEscorts");
	}	
	
	function setFromEmail($input){$this->fromEmail = $input;}
	function setToEmail($input){$this->toEmail = $input;}
	function setSubject($input){$this->subject = $input;}
	function setBody($input){$this->body = $input;}
	function setEmailTitle($input){$this->emailTitle = $input;}
	function setAttachment($input){$this->attachment = $input;}
	
	function sendEmail(){
		$this->from($this->fromEmail, $this->emailTitle);
		$this->to($this->toEmail);
		$this->subject($this->subject);
		$this->message($this->body);
		if($this->attachment){
			$this->attach($this->attachment);
		}
		
		if( ENVIRONMENT == 'development' ){
			$this->sendEmail2();
		}else{
			$this->send();
		}	
	}
	
	function sendEmail2(){
		require_once("PHPMailer/class.phpmailer.php");
		
		try {
			$mail = new PHPMailer(true); 
			$mail->IsSMTP(); // telling the class to use SMTP
			$mail->SMTPDebug  = 1; // enables SMTP debug information (for testing)               
			$mail->SMTPAuth   = true;                  // enable SMTP authentication
			$mail->SMTPSecure = "ssl";                 // sets the prefix to the servier
			$mail->Host       = "smtp.gmail.com";      // sets GMAIL as the SMTP server
			$mail->Port       = 465;   
			$mail->Username   = "auto.email.sender.gate2@gmail.com";     // SMTP server username
			$mail->Password   = "admine2#";            // SMTP server password

			$mail->From       = $this->fromEmail;
			$mail->FromName   = $this->emailTitle;

			$to = $this->toEmail;

			$mail->AddAddress($to);

			$mail->Subject  = $this->subject;
			
			if($this->attachment){
				$mail->AddAttachment($this->attachment);
			}
			
			$body = $this->body;
			$mail->MsgHTML($body);

			$mail->IsHTML(true); // send as HTML

			$mail->Send();
			//echo 'Message has been sent.';
		} catch (phpmailerException $e) {
			//echo $e->errorMessage();
		}
	}
	
	function test(){
		$emailContent = $this->CI->load->view('home/order_template', '', TRUE);
		echo $emailContent;
	}
	
	function loadEmailTemplate($slug){
		$langCode = get_language_code();
		$file = $slug."__".$langCode.".php";
		
		if(!is_file("./addons/shared_addons/modules/home/views/email_templates/$file")){
			return $this->CI->load->view("home/email_templates/{$slug}__en", '', TRUE);
		}else{
			return $this->CI->load->view("home/email_templates/{$slug}__{$langCode}", '', TRUE);
		}
	}
	
	function sendEmailToUser_escortRegister($userId){
		$USER = clone_( $this->CI->user_entity->init('id',$userId) );
		$slug = "user_create_new_account";
		
		$template = $this->CI->module_helper->getTemplateMail( $slug );
		$orgArr = array( "{###USERNAME###}", "{###PASSWORD###}" , "{###LINK###}" );
		
		$activated_link = site_url("registration/activated_account?code=".$USER->getActivatedCode());
		$link = "<a href='$activated_link'>$activated_link</a>";
		
		$rplArr = array( $USER->getUserName() , $USER->getPassword(),$link );
		
		//$body = str_replace( $orgArr , $rplArr , $template['body'] );
		$bodyFile = $this->loadEmailTemplate($slug);
		$body = str_replace( $orgArr , $rplArr , $bodyFile );
		$subject = language_translate( $template['subject'] );
		
		$emailContent = $this->CI->load->view('home/email_template', '', TRUE);
		$emailBody = str_replace( array( '###SUBJECT###','###BODY_OF_MESSAGE###') , array($subject, $body) , $emailContent);
		
		$this->setToEmail($USER->getEmail());
		$this->setSubject($subject);
		$this->setBody($emailBody);
		
		$this->sendEmail();
	}
	
	function sendEmailToUser_forgotAccountDetails($userId){
		$USER = clone_( $this->CI->user_entity->init('id',$userId) );
		$slug = 'forgot_account_details_email_sender';
		
		$template = $this->CI->module_helper->getTemplateMail( $slug );
		//$body = $template['body'];
		$body = $this->loadEmailTemplate($slug);
		$subject = language_translate( $template['subject'] );
		
		$body = str_replace(array('{###USERNAME###}','{###PASSWORD###}'),
							 array($USER->getUserName(), $USER->getPassword()), $body);
		
		$emailContent = $this->CI->load->view('home/email_template', '', TRUE);
		$emailBody = str_replace( array( '###SUBJECT###','###BODY_OF_MESSAGE###') , array($subject, $body) , $emailContent);
							 
		$this->setToEmail($USER->getEmail());
		$this->setSubject($subject);
		$this->setBody($emailBody);
		
		$this->sendEmail();
	}
	
	function sendEmailToUser_confirmEmailChanged($userId){
		$USER = clone_( $this->CI->user_entity->init('id',$userId) );
		$slug = 'user_change_email_confirm';
		
		$template = $this->CI->module_helper->getTemplateMail( $slug );
		//$body = $template['body'];
		$body = $this->loadEmailTemplate($slug);
		$subject = language_translate( $template['subject'] );
		
		$link = site_url('authorization/email_confirm').'?id='.$USER->getId().'&s='.md5($USER->getUserName());
		$sLink = "<a href='$link'>".$link."</a>";
		$body = str_replace(array('{###LINK###}'),
							 array($sLink), $body);
		
		$emailContent = $this->CI->load->view('home/email_template', '', TRUE);
		$emailBody = str_replace( array( '###SUBJECT###','###BODY_OF_MESSAGE###') , array($subject, $body) , $emailContent);
			
		$this->setToEmail($USER->getEmailChanged());
		$this->setSubject($subject);
		$this->setBody($emailBody);
		
		$this->sendEmail(); 
	}
	
    /**
	//deprecated
	function sendEmailToUser_newContractCreated($payment_history_id, $invoice_id){
		$PAYMENT_HISTORY = $this->CI->payment_history->init('id',$payment_history_id);
		$USER = $this->CI->user_entity->init('id',$PAYMENT_HISTORY->user_id);
		$slug = "send_email_to_user_create_new_contract";
		
		$template = $this->CI->module_helper->getTemplateMail( $slug );
		$body = $template['body'];
		$subject = $template['subject'];
		
		$user_type = $USER->getPermissionSlug();
		if($user_type == 'escort'){
			$ESCORT = $this->CI->escort_entity->init('user_id',$USER->getId());
			$PAYMENT = $this->CI->payment_log_entity->getCurrentServiceUnPaid($ESCORT->getId());
			$subscription_id = $this->CI->payment_log_entity->getServicesTypeUnPaid($ESCORT->getId(), 'SUBS');
			$myPlaceListArray = array_filter( explode(',', $this->CI->payment_log_entity->getServicesTypeUnPaid($ESCORT->getId(), 'PLACE')) );
			$myPackListArray = array_filter( explode(',', $this->CI->payment_log_entity->getServicesTypeUnPaid($ESCORT->getId(), 'PACK')) );
			$myPriorityListArray = array_filter( explode(',', $this->CI->payment_log_entity->getServicesTypeUnPaid($ESCORT->getId(), 'PRI')) );
			
			$iCount = 0;
		}else{
			$PAYMENT = $this->CI->payment_log_entity->getCurrentServiceUnPaid_Agent($USER->getId());
			$subscription_id = $this->CI->payment_log_entity->getServicesTypeUnPaid_Agent($USER->getId(), 'SUBS');
			$myPlaceListArray = array_filter( explode(',', $this->CI->payment_log_entity->getServicesTypeUnPaid_Agent($USER->getId(), 'PLACE')) );
			$myPackListArray = array_filter( explode(',', $this->CI->payment_log_entity->getServicesTypeUnPaid_Agent($USER->getId(), 'PACK')) );
			$myPriorityListArray = array_filter( explode(',', $this->CI->payment_log_entity->getServicesTypeUnPaid_Agent($USER->getId(), 'PRI')) );
			
			$AGENT_DISCOUNT = $this->CI->volume_discount_entity->getDiscountOfAgent( $USER->getId(), $USER->getEscortsApplyNumber() );
			$iCount = 0;
		}
		
		$net_amount = 0;
		
		$html = '';
		$html .= "<table width=\"100%\">
					<thead>
						<th>".language_translate('services_page_table_head_servicename')."</th>
						<th>".language_translate('services_page_table_head_details')."</th>
						<th>".language_translate('services_page_table_head_period')."</th>
						<th style=\"text-align:right;\">".language_translate('services_page_table_head_priceeuro')."</th>
					</thead>
					<tbody>";
		if($subscription_id){
			if($user_type == 'agent'){
				$SUB = $this->CI->payment_log_entity->checkServiceExisted_Agent($USER->getId(), 'SUBS', $subscription_id);
			}else{
				$SUB = $this->CI->payment_log_entity->checkServiceExisted($ESCORT->getId(), 'SUBS', $subscription_id);
			}
			$sub_period = $SUB ? $SUB->getLatestPeriod() : 1;
			$subs_array = getSubcriptionData_ioc($subscription_id);
			$iCount++;
			$html .="<tr>	
						<td>".language_translate('services_page_subscription')."</td>
						<td>".$subs_array[0]."</td>
						<td>".$sub_period."</td>
						<td style=\"text-align:right;\">".$SUB->getPaymentPrice()."</td>
					</tr>";
			$net_amount += 	$SUB->getPaymentPrice();	
		}
				
		foreach($myPlaceListArray as $k){
			$placeInfo = getPlaceListDataInfoById($k);
			if($placeInfo){
				$id=$placeInfo['id'];
				if($user_type == 'agent'){
					$PLACE = $this->CI->payment_log_entity->checkServiceExisted_Agent($USER->getId(), 'PLACE', $id);
				}else{
					$PLACE = $this->CI->payment_log_entity->checkServiceExisted($ESCORT->getId(), 'PLACE', $id);
				}
				$place_period = $PLACE ? $PLACE->getLatestPeriod() : 1;
				$iCount++;
				$html .= "<tr> 
							<td>".language_translate('services_page_where_do_you_work')."</td>
							<td>".$placeInfo['country']." /".$placeInfo['state']." /".$placeInfo['province']." /".$placeInfo['city']." 
							</td>
							<td>".$place_period." 
							</td>
							<td style=\"text-align:right;\">".$PLACE->getPaymentPrice()."</td>
						</tr>";
				$net_amount += 	$PLACE->getPaymentPrice();		
			}
		}
				
		foreach($myPackListArray as $k){
			$id=$k;
			if($user_type == 'agent'){
				$PACK = $this->CI->payment_log_entity->checkServiceExisted_Agent($USER->getId(), 'PACK', $id);
			}else{
				$PACK = $this->CI->payment_log_entity->checkServiceExisted($ESCORT->getId(), 'PACK', $id);
			}
			$pack_period = $PACK ? $PACK->getLatestPeriod() : 1;
			$pack_array = getPackListData_ioc($id);
			$iCount++;
					 
			$html	.=	"<tr>
							<td>".language_translate('services_page_add_a_pack')."</td>
							<td>".$pack_array[0]."</td>
							<td>".$pack_period."</td>
							<td style=\"text-align:right;\">".$PACK->getPaymentPrice()."</td>
						</tr>";
			$net_amount += 	$PACK->getPaymentPrice();			
		}
				
		foreach($myPriorityListArray as $k){
			$id=$k;
			if($user_type == 'agent'){
				$PRI = $this->CI->payment_log_entity->checkServiceExisted_Agent($USER->getId(), 'PRI', $id);
			}else{
				$PRI = $this->CI->payment_log_entity->checkServiceExisted($ESCORT->getId(), 'PRI', $id);
			}	
			$pri_period = $PRI ? $PRI->getLatestPeriod() : 1;
			$pri_array = getPriorityData_ioc($id);
			$iCount++;
						 
			$html	.=	"<tr>
							<td>".language_translate('services_page_priority')."</td>
							<td>".$pri_array[0]." </td>
							<td>".$pri_period." </td>
							<td style=\"text-align:right;\">".$PRI->getPaymentPrice()."</td>
						</tr>";
			$net_amount += 	$PACK->getPaymentPrice();				
		}
		$html	.= "<tr>
					<td colspan=3></td>
					<td style=\"text-align:right;\">".$PAYMENT."</td>
				</tr>
			</tbody>
		</table>";
		
		if($user_type == 'agent'){
			if($iCount AND $AGENT_DISCOUNT){
				$unit = ( $AGENT_DISCOUNT->getDiscountUnit() == '%' ) ? '%':'&euro;';
				$discount_info = $this->CI->payment_log_entity->getNetAmountOfAgent($USER->getId(),$USER->getEscortsApplyNumber());
				$html .= "<table width=\"100%\">
							<tr>
							<td width=\"50%\">".
								language_translate('services_page_your_discount_info') ."</td>" 
						 	."<td>".$AGENT_DISCOUNT->getDiscountAmountPerRegister().$unit."</td></tr>"
							."<tr><td>".language_translate('services_page_escorts_apply_number')."</td>"
							."<td>".$USER->getEscortsApplyNumber()."</td></tr>"
							."<tr><td>".language_translate('services_page_net_amount')."</td>"
							."<td>".number_format($net_amount,2)."&euro;</td></tr>"
							."</table>";
					
			}		
		}else{
		  	$DISCOUNT= $this->CI->discount_ticket_entity->getDiscountEscortByPromotionCode($ESCORT->getPromotionCode(),$ESCORT->getId()); 
			if($iCount){	
				$discount = ($DISCOUNT) ?  $DISCOUNT->name : '';
				$discount_info = $this->CI->payment_log_entity->getNetAmountOfEscort($ESCORT->getId());
				$html .= "<table width=\"100%\">
						<tr>
						<td width=\"50%\">".	
							language_translate('services_page_your_promotion_code')."</td>"
						."<td>".$discount."</td></tr>"	
						."<tr><td>".language_translate('services_page_net_amount')."</td>"
						."<td>".number_format($net_amount,2)."&euro;</td></tr>"
						."</table>";
			}
		}
		
		$html .= "<br/>";
		$records = $this->CI->escort_news_entity->getNewsByCategoryName('Payment Info');
		foreach($records as $item){
			$html .= $item->news;
		}
		
		$body = str_replace('{###INFORMATION###}', $html, $body); 
		
		$emailContent = $this->CI->load->view('home/email_template', '', TRUE);
		$emailBody = str_replace( array( '###SUBJECT###','###BODY_OF_MESSAGE###') , array($subject, $body) , $emailContent);
		
		$this->setToEmail($USER->getEmail());
		$this->setSubject($subject);
		$this->setBody($emailBody);
		
		$this->sendEmail();
	}
	**/
    
    
	function sendEmailToUser_sendOrder($history_id, $invoice_id){
		$PAYMENT_HISTORY = $this->CI->payment_history->init('id',$history_id);
		$USER = $this->CI->user_entity->init('id',$PAYMENT_HISTORY->user_id);
		$slug = "send_email_to_user_create_new_contract";
		
		$template = $this->CI->module_helper->getTemplateMail( $slug );
		 
		$subject = language_translate( $template['subject'] );
		
		$tax = $this->CI->escort_invoice_lines_m->getTaxOfCountry($USER->getId());
		
		$payment_log_array = array_filter(explode(',',$PAYMENT_HISTORY->getPaymentIds()));
		$info = '';
		
		$totalVolumnDiscount = $totalPeriodDiscount = $totalPromoDiscount = $totalPrice = 0;
		foreach($payment_log_array as $item){
			$PAY_LOG = $this->CI->payment_log_entity->init('id',$item);
			
			if($PAY_LOG->getServiceType() == 'SUBS'){
				$subs_array = getSubcriptionData_ioc($PAY_LOG->type_id);
				$price = euroCurrencyFormat( number_format( ((100-$tax)/100) * $PAY_LOG->payment_price, 2 ) );
				$info .= "<tr>";
				$info .= "<td>".$subs_array[0]."</td>";
				$info .= "<td>".$price."</td>";
				$info .= "<td>".$PAY_LOG->period."</td>";
				$info .= "</tr>";
				
				$totalVolumnDiscount += $PAY_LOG->discount_volumn_price;
				$totalPeriodDiscount += $PAY_LOG->discount_period_price;
				$totalPromoDiscount += $PAY_LOG->discount_promo_price;
				$totalPrice += $price;
			}
			
			if($PAY_LOG->getServiceType() == 'PLACE'){
				$placeInfo = getPlaceListDataInfoById($PAY_LOG->type_id);
				$desc = $placeInfo['country'];
				if($placeInfo['state']){
					$desc .= "/".$placeInfo['state'];
				}	
				if($placeInfo['province']){
					$desc .= "/".$placeInfo['province'];
				}
				if($placeInfo['city']){
					$desc .= "/".$placeInfo['city'];
				}
				$price = euroCurrencyFormat( number_format( ((100-$tax)/100) * $PAY_LOG->payment_price, 2 ) );
				$info .= "<tr>";
				$info .= "<td>".$desc."</td>";
				$info .= "<td>".$price."</td>";
				$info .= "<td>".$PAY_LOG->period."</td>";
				$info .= "</tr>";
				
				$totalVolumnDiscount += $PAY_LOG->discount_volumn_price;
				$totalPeriodDiscount += $PAY_LOG->discount_period_price;
				$totalPromoDiscount += $PAY_LOG->discount_promo_price;
				$totalPrice += $price;
			}
			
			if($PAY_LOG->getServiceType() == 'PACK'){
				$pack_array = getPackListData_ioc($PAY_LOG->type_id);
				$price = euroCurrencyFormat( number_format( ((100-$tax)/100) * $PAY_LOG->payment_price, 2 ) );
				$info .= "<tr>";
				$info .= "<td>".$pack_array[0]."</td>";
				$info .= "<td>".$price."</td>";
				$info .= "<td>".$PAY_LOG->period."</td>";
				$info .= "</tr>";
				
				$totalVolumnDiscount += $PAY_LOG->discount_volumn_price;
				$totalPeriodDiscount += $PAY_LOG->discount_period_price;
				$totalPromoDiscount += $PAY_LOG->discount_promo_price;
				$totalPrice += $price;
			}
			
			if($PAY_LOG->getServiceType() == 'PRI'){
				$pri_array = getPriorityData_ioc($PAY_LOG->type_id);
				$price = euroCurrencyFormat( number_format( ((100-$tax)/100) * $PAY_LOG->payment_price, 2 ) );
				$info .= "<tr>";
				$info .= "<td>".$pri_array[0]."</td>";
				$info .= "<td>".$price."</td>";
				$info .= "<td>".$PAY_LOG->period."</td>";
				$info .= "</tr>";
				
				$totalVolumnDiscount += $PAY_LOG->discount_volumn_price;
				$totalPeriodDiscount += $PAY_LOG->discount_period_price;
				$totalPromoDiscount += $PAY_LOG->discount_promo_price;
				$totalPrice += $price;
			}
		}
		$vatTax = $PAYMENT_HISTORY->net_amount - $totalVolumnDiscount - $totalPeriodDiscount - $totalPromoDiscount - $totalPrice;
		$vatTax = ($vatTax>=0) ? $vatTax:0;
		if($vatTax == 0){
			$vatTax = $PAYMENT_HISTORY->net_amount * $tax/100;
		}
		
		$infotax = "<tr>";
		$infotax .= "<td></td>";
		//$infotax .= "<td>".number_format( ($tax/100) * $PAYMENT_HISTORY->payment_price, 2 )."</td>";
		$infotax .= "<td>".euroCurrencyFormat( number_format( $vatTax, 2 ) )."</td>";
		$infotax .= "<td>".euroCurrencyFormat( number_format(  $PAYMENT_HISTORY->net_amount, 2 ) )."</td>";
		$infotax .= "</tr>";
		
		$records = $this->CI->escort_news_entity->getNewsByCategoryName('Payment Info');
		$html = '';
		foreach($records as $item){
			$html .= $item->news;
		}
		
		$discount = '';
		$totalVolumnDiscount = euroCurrencyFormat( number_format($totalVolumnDiscount,2) );
		$totalPeriodDiscount = euroCurrencyFormat( number_format($totalPeriodDiscount,2) );
		$totalPromoDiscount = euroCurrencyFormat( number_format($totalPromoDiscount,2) );
		if($USER->getPermissionSlug() == USER_TYPE_AGENT){
			$discount .= language_translate('contract_volumn_discount');
			$discount .= ' '.$totalVolumnDiscount;	
			$discount .= "<br/>";
			$discount .= language_translate('services_page_total_period_discount');
			$discount .= ' '.$totalPeriodDiscount;	
		}else{
			$discount .= language_translate('services_page_promo_discount');
			$discount .= ' '.$totalPromoDiscount;	
			$discount .= "<br/>";
			$discount .= language_translate('services_page_total_period_discount');
			$discount .= ' '.$totalPeriodDiscount;	
		}
		
		$moreinfo = '';
		$moreinfo .= language_translate('contract_start_date').": ";
		$moreinfo .= sysDateFormat( $PAYMENT_HISTORY->start_date, DATE_FORMAT);
		$moreinfo .= "<br/>";
		$moreinfo .= language_translate('contract_to_date').": ";
		$moreinfo .= sysDateFormat( $PAYMENT_HISTORY->end_date, DATE_FORMAT);
		
		if($USER->getPermissionSlug() == USER_TYPE_AGENT){
			$moreinfo .= "<br/>";
			$moreinfo .= language_translate('services_page_escorts_apply_number').": ";
			$moreinfo .= $PAYMENT_HISTORY->escorts_apply_number;
		}
		
		$emailContent = $this->CI->load->view('home/order_template', '', TRUE);
		$emailBody = str_replace( 
						array( '###ID###','###CLIENT_NAME###', '###CLIENT_ADDRESS###', '###CLIENT_EMAIL###', 
								'###LINES###', '###RESULT###', '###TAX###','###BODY###', '###MOREINFO###', '###DISCOUNTINFO###') ,
						array($history_id, $USER->name, $USER->address, $USER->email, 
								$info, $infotax, $tax.'%', $html, $moreinfo, $discount) ,
						$emailContent
					);
		
		$this->setToEmail($USER->getEmail());
		$this->setSubject($subject);
		$this->setBody($emailBody);
		
		$this->sendEmail();
	}
	
	//end class
}	

